package com.swjd.stack;

import java.util.Scanner;

/**
 * 数组模拟栈
 *
 * @author 刘涛
 * @create 2021/9/24 19:41
 */
public class ArrayStackDemo {
    public static void main(String[] args) {
        //测试ArrayStack
        ArrayStack stack = new ArrayStack(4);
        String key = "";
        boolean loop = true;
        Scanner scanner = new Scanner(System.in);
        while (loop) {
            System.out.println("show：显示栈");
            System.out.println("exit：退出程序");
            System.out.println("push：添加数据到栈");
            System.out.println("pop：从栈中取出数据");
            System.out.println("请输入你的选择");
            key = scanner.next();
            switch (key) {
                case "show":
                    stack.list();
                    break;
                case "push":
                    System.out.println("请输入一个数");
                    int i = scanner.nextInt();
                    stack.push(i);
                    break;
                case "pop":
                    try {
                        int pop = stack.pop();
                        System.out.println("出栈的数据是" + pop);
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    }
                    break;
                case "exit":
                    scanner.close();
                    loop = false;
                    System.out.println("程序退出了！");
                    break;
            }

        }
    }
}

//定义一个ArrayStack栈
class ArrayStack {
    private int maxSize;//栈容量
    private int[] stack;//模拟栈的数组
    private int top = -1;//栈顶 没有数据时初始化为-1

    public ArrayStack(int maxSize) {
        this.maxSize = maxSize;
        stack = new int[this.maxSize];
    }

    /**
     * 是否栈满
     *
     * @return true满 false未满
     */
    public boolean isFull() {
        return top == maxSize - 1;
    }

    /**
     * 是否栈空
     *
     * @return true满 false未满
     */
    public boolean isEmpty() {
        return top == -1;
    }

    /**
     * 入栈
     *
     * @param value 需要入栈的值
     */
    public void push(int value) {
        //先判断栈是否满了
        if (isFull()) {
            System.out.println("栈满！");
            return;
        }
        top++;
        stack[top] = value;
    }

    /**
     * 出栈
     *
     * @return 栈顶代码
     */
    public int pop() {
        if (isEmpty()) {
            //抛出异常处理
            throw new RuntimeException("栈空！");
        }
        int value = stack[top];
        top--;
        return value;
    }

    /**
     * 遍历
     */
    public void list() {
        if (isEmpty()) {
            System.out.println("栈空！");
            return;
        }
        for (int i = top; i >= 0; i--) {
            System.out.println(i + "：" + stack[i]);
        }
    }
}
